#include "pch.h"
#include "UITrayIconWnd.h"
#include "GaojieDriveApp.h"
#include "AppConfig.h"
#include "UIWndManager.h"

CUITrayIconWnd::CUITrayIconWnd()
	: m_uTaskbarCreated(RegisterWindowMessageW(L"TaskbarCreated"))
	, m_hMenu(NULL)
{
	AssertInUIThread();
}

CUITrayIconWnd::~CUITrayIconWnd()
{
	AssertInUIThread();

	if (m_hMenu)
		DestroyMenu(m_hMenu);
}

LRESULT CUITrayIconWnd::OnCreate(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
	AddTrayIcon();
	return 0;
}

LRESULT CUITrayIconWnd::OnDestroy(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
	DelTrayIcon();
	return 0;
}

LRESULT CUITrayIconWnd::OnTrayNotify(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
	switch (LOWORD(lParam))
	{
	case WM_LBUTTONDBLCLK:
		GetApp()->GetUIWndManager()->ShowSettings();
		break;

	case WM_RBUTTONUP:
		OnContextMenu(LOWORD(wParam), HIWORD(wParam));
		break;
	}

	return 0;
}

LRESULT CUITrayIconWnd::OnTaskbarCreated(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
	AddTrayIcon();
	return 0;
}

LRESULT CUITrayIconWnd::OnOpenFolder(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled)
{
	ShellExecuteW(NULL, NULL, GetApp()->GetAppConfig()->GetClientRoot().c_str(), NULL, NULL, SW_SHOWNORMAL);
	return 0;
}

LRESULT CUITrayIconWnd::OnSettings(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled)
{
	GetApp()->GetUIWndManager()->ShowSettings();
	return 0;
}

LRESULT CUITrayIconWnd::OnAbout(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled)
{
	GetApp()->GetUIWndManager()->ShowAbout();
	return 0;
}

LRESULT CUITrayIconWnd::OnExit(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled)
{
	GetApp()->GetUIWndManager()->DestroyWnds();
	return 0;
}

void CUITrayIconWnd::OnFinalMessage(HWND)
{
	delete this;
	PostQuitMessage(0);
}

void CUITrayIconWnd::AddTrayIcon()
{
	AssertInUIThread();

	NOTIFYICONDATAW nid = { sizeof(nid) };
	nid.hWnd = m_hWnd;
	nid.uID = IDR_MAINFRAME;
	nid.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP | NIF_SHOWTIP;
	nid.uCallbackMessage = WM_TRAY_NOTIFY;
	nid.hIcon = GetApp()->GetUIWndManager()->GetMainIcon();
	wcscpy_s(nid.szTip, L"GaojieDrive");
	Shell_NotifyIconW(NIM_ADD, &nid);

	nid.uVersion = NOTIFYICON_VERSION_4;
	Shell_NotifyIconW(NIM_SETVERSION, &nid);
}

void CUITrayIconWnd::DelTrayIcon()
{
	AssertInUIThread();

	NOTIFYICONDATAW nid = { sizeof(nid) };
	nid.hWnd = m_hWnd;
	nid.uID = IDR_MAINFRAME;
	Shell_NotifyIconW(NIM_DELETE, &nid);
}

void CUITrayIconWnd::OnContextMenu(int x, int y)
{
	AssertInUIThread();

	if (m_hMenu == NULL)
		m_hMenu = LoadMenu(GetApp()->GetInstance(), MAKEINTRESOURCE(IDC_GAOJIEDRIVE));

	HMENU hSubMenu;
	if (m_hMenu && (hSubMenu = GetSubMenu(m_hMenu, 0)))
	{
		SetForegroundWindow(m_hWnd);
		TrackPopupMenuEx(hSubMenu, TPM_LEFTBUTTON | TPM_LEFTALIGN, x, y, m_hWnd, NULL);
	}
}
